// pages/feastPage/notOwner/notOwner.js
var netWork = require('../../../utils/netWork.js');
var model = require('../../../model/model.js')
var api = require('../../../utils/api.js');

const log = require('../../../utils/logs.js');

var item = {};
var addressInfo = {};
var feastInfo = null;
var isClick = true;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagesUrl: getApp().globalData.imagesUrl,
    topHeight: 0,
    // address:'请选择省/市/区',
    address: '请选择省市区',
    ani: 0, //动画是否执行
    readRule: false,
    readPrivate: false,
    date: '',
    isEnd: 1,
    feastInfo: null,
    getPrize: false,
    showAlert: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    try {
      const {
        SDKVersion = ''
      } = wx.getSystemInfoSync();
      // 获取系统信息
      const that = this;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            addHeight: (res.screenHeight * res.pixelRatio - 1334) / 6
          });
        }
      });
      console.log(that.data.addHeight)
      log.info(SDKVersion)
      const compatibility = util.compareVersion(SDKVersion, '2.2.2');
      log.info(compatibility)
      if (compatibility == -1) {
        wx.showModal({
          content: '您的微信版本过低，请升级后再来吧~',
          confirmText: '我知道了',
          showCancel: false
        });
        return;
      }
    } catch (e) {}
    try {
      // 检测是否可以调用getUpdateManager检查更新
      if (!wx.canIUse("getUpdateManager")) return;
      let updateManager = wx.getUpdateManager();
      // 获取全局唯一的版本更新管理器，用于管理小程序更新
      updateManager.onCheckForUpdate(function (res) {
        log.info(res)
        // 监听向微信后台请求检查更新结果事件
        log.info("是否有新版本：" + res.hasUpdate);
        if (res.hasUpdate) {
          //如果有新版本
          // 小程序有新版本，会主动触发下载操作
          updateManager.onUpdateReady(function () {
            //当新版本下载完成，会进行回调
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，单击确定重启小程序',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启小程序
                  updateManager.applyUpdate();
                }
              }
            })
          })
          // 小程序有新版本，会主动触发下载操作（无需开发者触发）
          updateManager.onUpdateFailed(function () {
            //当新版本下载失败，会进行回调
            wx.showModal({
              title: '提示',
              content: '检查到有新版本，但下载失败，请稍后尝试',
              showCancel: false,
            })
          })
        }
      });
    } catch (e) {
      e
    }
    //高度处理
    let topHeight = wx.getStorageSync('statusBarHeight') + wx.getStorageSync('navigationBarHeight');
    this.setData({
      topHeight: topHeight,
      icon: 'common/loading',
    });
    api.judgeNetworkStatus(function (res) {
      if ("none" == res) return;
    })
    var myDate = new Date();
    var time = myDate.toLocaleDateString().split('/').join('-');
    this.setData({
      date: time
    });
    //查询基础数据
    if (options.activityInfo) {
      feastInfo = JSON.parse(options.activityInfo);
      this.setData({
        feastInfo: JSON.parse(options.activityInfo),
       
      })
      console.log(JSON.stringify(this.data.feastInfo))
    } else {

    }

  },
  onShow() {
    //查询奖品配置
    this.config();


  },
  getPrzie() {
    let openedCount = this.data.feastInfo.openedCount;
    let prizeId = '';
    let prizeName = '';
    //获取prizeid
    for (var i = 0; i < this.data.configList.length; i++) {
      if (openedCount >= this.data.configList[i].openedCount) {
        prizeId = this.data.configList[i].prizeId;
        prizeName = this.data.configList[i].prizeName;
      }
    }
    if (prizeId == '') {
      wx.showToast({
        title: '已开瓶数未达到领奖开瓶数！',
        icon: 'none',
        duration: 4000
      })
      return;
    }
    this.setData({
      getPrize: true,
      prizeId: prizeId,
      prizeName: prizeName
    });
  },
  canSave() {
    this.setData({
      getPrize: false,
      address: "请选择省市区"
    });

  },
  isLoading(isLoading, loadingText) {
    this.setData({
      isLoading: isLoading,
      loadingText: loadingText
    })

  },
  //表单提交按钮,校验
  formSubmit: function (e) {
    //防止重复点击或者点击过快
    console.log("点击了");
    if (!isClick) {
      console.log("重复返回~");
      return;
    }
    if (isClick) {
      isClick = false;
      //定时器
      setTimeout(function () {
        isClick = true;
      }, 3000); //3秒内不能重复点击
    }
    let userName = e.detail.value.userName;
    let phone = e.detail.value.phone;
    let detailAddress = e.detail.value.detailAddress;
    if (userName.trim() == "") {
      wx.showToast({
        title: '请输入收件人姓名',
        icon: 'none'
      })
      return;
    }
     
    if (phone.trim() == "") {
      wx.showToast({
        title: '请输入手机号码',
        icon: 'none'
      })
      return;
    }

    let a = /^1\d{10}$/;
    if (!a.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号码',
        icon: 'none'
      })
      return;
    }
    if (this.data.address == '请选择省市区') {
      wx.showToast({
        title: '请选择地区',
        icon: 'none'
      })
      return;
    }
    if (detailAddress.trim() == "") {
      wx.showToast({
        title: '请输入详细地址',
        icon: 'none'
      })
      return;
    }
    this.setData({
      formValue: e.detail.value
    })
    let materialInfo = {};
    materialInfo['receiveProvinceId'] = addressInfo.receiveProvinceId;
    materialInfo['receiveCityId'] = addressInfo.receiveCityId;
    materialInfo['receivceDistrictId'] = addressInfo.receivceDistrictId;
    materialInfo['receiveProvinceName'] = addressInfo.receiveProvinceName;
    materialInfo['receiveCityName'] = addressInfo.receiveCityName;
    materialInfo['receiveDistrictName'] = addressInfo.receiveDistrictName;
    materialInfo['receiveName'] = userName;
    materialInfo['receivePhone'] = phone;
    materialInfo['receiveAddress'] = detailAddress;
    // wx.setStorageSync('materialInfo', materialInfo)
    this.revicePrize();

  },
  /**
   * 点击领取,进行实物奖兑奖
   */
  revicePrize: function () {


    this.isLoading(true, "正在提交...");
    const that = this;
    //兑奖
    netWork.POST('receiveMatter', {
      data: {
        userId: wx.getStorageSync('userId'),
        prizeOrderId: that.data.feastInfo.materialInfo.prizeOrderId,
        prizeId: that.data.prizeId,
        positioningStyle: 0,
        positioningType: 0,
        latitude: wx.getStorageSync('latitude'),
        longitude: wx.getStorageSync('longitude'),
        speed: wx.getStorageSync('speed'),
        accuracy: wx.getStorageSync('accuracy'),
        receiveName:  that.data.formValue.userName, //收货人
        receivePhone: that.data.formValue.phone, //收货电话
        receiveProvinceId: addressInfo.receiveProvinceId, //省
        receiveCityId: addressInfo.receiveCityId, //市
        receivceDistrictId: addressInfo.receivceDistrictId, //区
        receiveProvinceName: addressInfo.receiveProvinceName,
        receiveCityName: addressInfo.receiveCityName,
        receiveDistrictName: addressInfo.receiveDistrictName,
        receiveAddress: that.data.formValue.detailAddress, //地址
        source: 1, //兑奖来源，1-正常流程兑奖 2-中奖记录兑奖
      },
      success: function (res) {
        that.isLoading(false);
        if (res.data.retCode == undefined) {
          //错误提示
          that.setData({
            showAlert: true,
            alertContent: '操作失败,请稍后重试'
          })
        }
        if (res.data.retCode == "0000") {
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 3000
          })
          that.setData({
            getPrize: false
          })
          that.queryInfo();
        } else if (res.data.retCode == "10052") {
          setTimeout(function () {
            wx.showToast({
              title: '收货信息不支持表情等特殊字符，请修改后再提交哦~',
              icon: 'none',
              duration: 3000
            })
          }, 100)
        } else {
          let msg = res.data.retInfo==null|| res.data.retInfo==''? res.data.retMsg:res.data.retInfo;
          //错误提示页
          that.setData({
            showAlert: true,
            alertContent: msg+'[' + res.data.retCode + ']'
          })
        }

      },
      fail: function (res) {
        that.isLoading(false);
        //错误提示页
        that.setData({
          showAlert: true,
          alertContent: '操作失败,请稍后重试'
        })
      }
    });
  },
  feastList() {
    wx.navigateTo({
      url: '../feastList/feastList',
    })
  },
  onHide() {
    setTimeout(() => {
      this.setData({
        feastInfo: null
      })
    }, 800)
  },

  config() {
    const that = this;
    that._freshing = true;
    that.isLoading(true, '加载中...')
    netWork.POST_Json('banquet/config', {
      data: {
        qrcodeAPublish: wx.getStorageSync('qrCodeFeast'),
      },
      success: function (res) {
        that.isLoading(false)
        if (res.data.retCode == undefined) {
          wx.showToast({
            title: '操作失败，稍后重试',
            icon: 'none'
          })
        }
        if (res.data.retCode == '0000') {
          let newArr = [];
          for (var i = 0; i < res.data.data.length; i++) {
            if (res.data.data[i].sendType == 2) {
              newArr.push(res.data.data[i]);
            }
          }
          that.setData({
            configList: newArr
          });
          if (that.data.feastInfo == null) {
            that.queryInfo();
          } else { //显示第几个
            let index = -1;
            for (var i = 0; i < that.data.configList.length; i++) {
              if (that.data.feastInfo.openedCount >= that.data.configList[i].openedCount) {
                index = i;

              }
            }
            that.setData({
              index: index
            })
          }
        } else {
          wx.showToast({
            title: '操作失败，稍后重试',
            icon: 'none'
          })
        }
      },
      fail: function (res) {
        that.isLoading(false)
        wx.showToast({
          title: '操作失败，稍后重试',
          icon: 'none'
        })
      }
    });
  },
  scan() {
    wx.navigateTo({
      url: '../activatedDetails/activatedDetails',
    })
  },
  openList() {
    wx.navigateTo({
      url: '../openPrizeList/openPrizeList?activityBanquetId=' + this.data.feastInfo.activityBanquetId,
    })
  },
  queryInfo() {
    const that = this;
    that.isLoading(true, '加载中...')
    netWork.POST_Json('banquet/info', {
      data: {
        qrcodeAPublish: wx.getStorageSync('qrCodeFeast'),
      },
      success: function (res) {
        that.isLoading(false)
        if (res.data.retCode == undefined) {
          wx.showToast({
            title: '操作失败，稍后重试',
            icon: 'none'
          })
        }
        if (res.data.retCode == '0000') {
          that.setData({
            feastInfo: res.data.data
          })
          console.log(JSON.stringify(that.data.feastInfo))
          let index = -1;
          for (var i = 0; i < that.data.configList.length; i++) {
            if (that.data.feastInfo.openedCount >= that.data.configList[i].openedCount) {
              index = i;

            }
          }
          that.setData({
            index: index
          })
        } else {
          wx.showToast({
            title: '操作失败，稍后重试',
            icon: 'none'
          })
        }
      },
      fail: function (res) {
        that.isLoading(false)
        wx.showToast({
          title: '操作失败，稍后重试',
          icon: 'none'
        })
      }
    });
  },
  //点击选择城市按钮显示picker-view
  translate: function (e) {
    console.log('点击了')
    model.animationEvents(this, 0, true, 400);
  },
  //隐藏picker-view
  hiddenFloatView: function (e) {
    model.animationEvents(this, 200, false, 400);
    if (e.target.dataset.id == '555') {
      return;
    }
    if (this.data.address == '请选择省/市/区' || JSON.stringify(addressInfo) == '{}' || (this.data.item.value[0] == 0 && this.data.item.value[1] == 0 && this.data.item.value[2] == 0)) {
      addressInfo = {
        "receiveProvinceId": '110000',
        "receiveCityId": '110100',
        "receivceDistrictId": '110101',
        "receiveProvinceName": '北京市',
        "receiveCityName": '北京市',
        "receiveDistrictName": '东城区'
      };

    }
    this.setData({
      address: addressInfo.receiveProvinceName + ' ' + addressInfo.receiveCityName + ' ' + addressInfo.receiveDistrictName,
      color: true
    })

  },
  //滑动事件
  bindChange: function (e) {
    model.updateAreaData(this, 1, e);
    item = this.data.item;
    addressInfo = {
      "receiveProvinceId": item.provinces[item.value[0]].id,
      "receiveCityId": item.citys[item.value[1]].id,
      "receivceDistrictId": item.countys[item.value[2]].id,
      "receiveProvinceName": item.provinces[item.value[0]].name,
      "receiveCityName": item.citys[item.value[1]].name,
      "receiveDistrictName": item.countys[item.value[2]].name
    };
  },
  //生命周期函数--监听页面初次渲染完成
  onReady: function (e) {
    // api.cancelLoading();
    //根据经纬度，获取省市区
    if (this.data.address == "" || this.data.address == '请选择省/市/区') {
      this.analysisArea(e);
    } else {
      var that = this;
      //请求数据
      model.updateAreaData(that, 0, e);
    }
  },
  feastRule() {
    let activityBanquetId = this.data.feastInfo.activityBanquetId;
    wx.navigateTo({
      url: '../feastRule/feastRule?activityBanquetId=' + activityBanquetId,
    })
  },
  ok() {
    this.setData({
      barcode: '',
      alertContent: '',
      showAlert: false
    })
  },
  handlerGobackClick(){
    let isMemberDay = wx.getStorageSync('isMemberDay');
    if(isMemberDay){
        wx.redirectTo({
            url: '/pages/jingdianPage/memberDayIndex/memberDayIndex',
          });
    }else{
        wx.redirectTo({
            url: '/pages/jingdianPage/index/index',
        });
    }
    wx.setStorageSync('productType', 1);
    wx.removeStorageSync('qrCode'); 
  }
})